<template>
  <el-dialog
    title="添加指标"
    :visible.sync="visible"
    width="90%"
    :before-close="handleClose"
    class="add-indicator-dialog"
  >
    <!-- 表格上方的过滤器 -->
    <div class="filter-bar">
      <div class="filter-left">
        <!-- <el-select
          v-model="filterForm.firstView"
          placeholder="一级视角"
          clearable
          style="width: 150px; margin-right: 10px;"
          @change="handleFilter"
        >
          <el-option
            v-for="item in firstLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-input v-model="filterForm.firstView" placeholder="一级视角" clearable style="width: 150px; margin-right: 10px;" @input="handleFilter" />
        <el-input v-model="filterForm.secondView" placeholder="二级视角" clearable style="width: 150px; margin-right: 10px;" @input="handleFilter" />
        <!-- <el-select
          v-model="filterForm.secondView"
          placeholder="二级视角"
          clearable
          style="width: 150px; margin-right: 10px;"
          @change="handleFilter"
        >
          <el-option
            v-for="item in secondLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        
        <el-input
          v-model="filterForm.indexName"
          placeholder="搜索指标"
          clearable
          style="width: 200px;"
          @input="handleFilter"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
    </div>
    
    <!-- 主表格 -->
    <el-table
      ref="tableRef"
      :data="filteredTableData"
      style="width: 100%; margin-top: 16px;"
      height="60vh"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column prop="style" label="样式" width="120">
        <template #default="{ row }">
          <el-select 
            v-model="row.style" 
            size="mini" 
            style="width: 100px;"
            popper-class="style-select-dropdown"
          >
            <el-option
              v-for="style in styleOptions"
              :key="style"
              :label="style"
              :value="style"
              @mouseenter.native="handleStyleHover(style, $event)"
              @mouseleave.native="handleStyleLeave"
            >
              <span>{{ style }}</span>
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      
      <el-table-column prop="groupIndex" label="分组" width="120">
        <template #default="{ row }">
          <el-input v-model="row.groupIndex" size="mini" />
        </template>
      </el-table-column>

      <el-table-column prop="orderIndex" label="排序" width="120">
        <template #default="{ row }">
          <el-input v-model="row.orderIndex" size="mini" type="number"/>
        </template>
      </el-table-column>
      
      <el-table-column prop="firstView" label="一级视角" min-width="120" />
      <el-table-column prop="secondView" label="二级视角" min-width="120" />
      <el-table-column prop="indexName" label="指标名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="unit" label="指标单位" min-width="100" />
      <el-table-column prop="year" label="指标年份" width="80" />
      <el-table-column prop="indexValue" label="指标值" min-width="120" />
      <el-table-column prop="coreRun" label="查询语句" min-width="300" show-overflow-tooltip>
        <!-- <template #default="{ row }">
          <div class="table-cell-content" :title="row.coreRun">
            {{ row.coreRun }}
            <div v-if="row.coreRun">
              <el-button type="text" size="mini" @click="handleEditQuery(row)">
                编辑
              </el-button>
            </div>
          </div>
        </template> -->
      </el-table-column>
      <el-table-column prop="departField" label="分区字段" min-width="120" />
      
      <el-table-column
        prop="mapUrl"
        label="地图链接"
        min-width="200"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div class="table-cell-content">
            <span v-if="row.mapDarknessUrl">
              <span>深色：</span>
              <span>{{ row.mapDarknessUrl }}</span>
            </span>
            <span v-if="row.mapTintUrl">
              <span>浅色：</span>
              <span>{{ row.mapTintUrl }}</span>
            </span>
            <span v-else>-</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="fieldJson" label="字段顺序" min-width="120" />
      <el-table-column prop="commonJudgeList" label="评价标准" min-width="200">
        <template #default="{ row }">
          <div class="judge-type-cell">
            <div class="judge-content">
              {{ renderJudgeList(row.commonJudgeList) }}
            </div>
            <div class="judge-actions" v-if="row.commonJudgeList && row.commonJudgeList.length > 0">
              <el-button type="text" size="mini" @click="handleEditJudge(row)">
                编辑
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="judgeResult" label="评价结果" min-width="200" show-overflow-tooltip />
      <el-table-column prop="indexDefine" label="指标定义" min-width="200" show-overflow-tooltip />
      <el-table-column prop="indexResult" label="指标结论" min-width="150" show-overflow-tooltip />
    </el-table>
    
    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <span class="selected-count">已选择 {{ selectedRows.length }} 项</span>
      <div>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确定
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { queryConfigByDistrictAndCatalogList } from '@/api/screen-management/indicator-config'

export default {
  name: 'AddIndicatorDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    preSelectedIds: {
      type: Array,
      default: () => []
    },
    areaCode: {
      type: String,
      default: ''
    },
    catalogId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      selectedRows: [],
      filterForm: {
        firstView: '',
        secondView: '',
        indexName: ''
      },
      // 样式选项
      styleOptions: [
        'ds1', 'ds2', 'ds3', 'ds4',
        'ds5', 'title',
        's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13',
        'chart'
      ],
      // 样式预览图片映射（测试图片）
      stylePreviewImages: {
        'ds1': '',
        'ds2': '',
        'ds3': '',
        'ds4': '',
        'ds5': require('@/assets/images/indicator-styles/ds5.png'),
        'title': require('@/assets/images/indicator-styles/title.png'),
        's1': require('@/assets/images/indicator-styles/s1.png'),
        's2': require('@/assets/images/indicator-styles/s2.png'),
        's3': require('@/assets/images/indicator-styles/s3.png'),
        's4': require('@/assets/images/indicator-styles/s4.png'),
        's5': require('@/assets/images/indicator-styles/s5.png'),
        's6': require('@/assets/images/indicator-styles/s6.png'),
        's7': require('@/assets/images/indicator-styles/s7.png'),
        's8': require('@/assets/images/indicator-styles/s8.png'),
        's9': require('@/assets/images/indicator-styles/s9.png'),
        's10': require('@/assets/images/indicator-styles/s10.png'),
        's11': '',
        's12': '',
        's13': '',
        'chart': require('@/assets/images/indicator-styles/chart_组合图.png'),
        // 'chart_条形图': require('@/assets/images/indicator-styles/style3.png'),
        // 'chart_组合图': require('@/assets/images/indicator-styles/style3.png'),
      },
      // 预览图片相关
      previewTooltip: null,
      // 一级视角选项
      firstLevelOptions: [
        { label: '经济发展', value: '经济发展' },
        { label: '社会发展', value: '社会发展' },
        { label: '环境质量', value: '环境质量' },
        { label: '基础设施', value: '基础设施' }
      ],
      // 二级视角选项
      secondLevelOptions: [
        { label: 'GDP', value: 'GDP' },
        { label: '人口', value: '人口' },
        { label: '空气质量', value: '空气质量' },
        { label: '交通', value: '交通' },
        { label: '教育', value: '教育' },
        { label: '医疗', value: '医疗' }
      ],
      // 模拟表格数据
      tableData: [],
      filteredTableData: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.visible = val
        if (val) {
          // 弹窗打开时重置数据并重新加载（resetData中会调用getIndicatorTableList）
          this.resetData()
        }
      },
      immediate: true
    },
    preSelectedIds: {
      handler() {
        if (this.visible) {
          // preSelectedIds变化时重新设置预选中项
          this.$nextTick(() => {
            this.setPreSelectedItems()
          })
        }
      }
    }
  },
  // mounted() {
  //   // 组件初始化时加载数据
  //   this.getIndicatorTableList()
  // },
  beforeDestroy() {
    // 组件销毁时清理tooltip
    this.removeTooltip()
  },
  methods: {
    getIndicatorTableList() {
      const params = {
        pageSize: 1000,
        pageIndex: 1,
        areaCode: this.areaCode,
        catalogId: this.catalogId
      }
      
      // 添加筛选参数
      if (this.filterForm.firstView) {
        params.firstView = this.filterForm.firstView
      }
      if (this.filterForm.secondView) {
        params.secondView = this.filterForm.secondView
      }
      if (this.filterForm.indexName) {
        params.indexName = this.filterForm.indexName
      }
      
      // 自定义序列化参数以确保数组格式正确
      const requestParams = { ...params }
      if (Array.isArray(requestParams.areaCode)) {
        // 将数组转换为逗号分隔的字符串
        requestParams.areaCode = requestParams.areaCode.join(',')
      }
      
      console.log('AddIndicatorDialog 请求参数 :>> ', requestParams)
      
      queryConfigByDistrictAndCatalogList(requestParams).then(res => {
        if (res.success) {
          this.tableData = res.data
          this.filteredTableData = [...this.tableData]
          
          // 数据加载完成后，重新设置预选中项
          if (this.visible && this.preSelectedIds && this.preSelectedIds.length > 0) {
            this.$nextTick(() => {
              this.setPreSelectedItems()
            })
          }
        } else {
          this.tableData = []
          this.filteredTableData = []
        }
      }).catch(err => {
        console.error('AddIndicatorDialog 查询失败:', err)
        this.tableData = []
        this.filteredTableData = []
      })
    },
    // 重置数据
    resetData() {
      this.selectedRows = []
      this.filterForm = {
        firstView: '',
        secondView: '',
        indexName: ''
      }
      // 重置筛选条件后重新加载数据
      this.getIndicatorTableList()
      this.$nextTick(() => {
        this.$refs.tableRef && this.$refs.tableRef.clearSelection()
      })
    },
    
    // 设置预选中的项
    setPreSelectedItems() {
      if (!this.preSelectedIds || this.preSelectedIds.length === 0) {
        return
      }
      
      // 清除现有选中状态
      this.$refs.tableRef && this.$refs.tableRef.clearSelection()
      this.selectedRows = []
      
      // 根据预选中ID找到对应的数据行并选中
      this.preSelectedIds.forEach(id => {
        const matchedRow = this.filteredTableData.find(row => 
          row.pkid === id || row.id === id
        )
        if (matchedRow) {
          this.$refs.tableRef && this.$refs.tableRef.toggleRowSelection(matchedRow, true)
          if (!this.selectedRows.find(row => (row.pkid || row.id) === id)) {
            this.selectedRows.push(matchedRow)
          }
        }
      })
      
    },
    
    // 处理过滤
    handleFilter() {
      // 重新调用API获取筛选后的数据
      this.getIndicatorTableList()
    },
    
    // 渲染评价标准列表
    renderJudgeList(judgeList) {
      if (!judgeList || judgeList.length === 0) {
        return ''
      }
      
      const getJudgeTypeText = (judgeType) => {
        const typeMap = {
          'between': '区间型',
          'top': '目标型',
          'bottom': '底线型',
          'normal': '普查型'
        }
        return typeMap[judgeType] || judgeType
      }
      
      const firstJudge = judgeList[0]
      const judgeTypeText = getJudgeTypeText(firstJudge.judgeType)
      
      const judgeItems = judgeList.map((judge) => {
        let rangeText = ''
        
        if (judge.judgeType === 'between') {
          rangeText = `${judge.judgeMinValue}-${judge.judgeMaxValue}`
        } else if (judge.judgeType === 'top') {
          rangeText = `>=${judge.judgeMinValue}`
        } else if (judge.judgeType === 'bottom') {
          rangeText = `<${judge.judgeMaxValue}`
        }
        
        return rangeText ? `${rangeText} ${judge.judgeName}` : judge.judgeName
      }).join('\n')
      
      return `${judgeTypeText}\n${judgeItems}`
    },
    
    // 编辑查询语句
    handleEditQuery(row) {
      this.$message.info('编辑查询语句功能待实现')
    },
    
    // 编辑评价标准
    handleEditJudge(row) {
      this.$message.info('编辑评价标准功能待实现')
    },
    
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    // 预览地图链接
    handlePreview(link) {
      window.open(link, '_blank')
    },
    
    // 确认选择
    handleConfirm() {
      // if (this.selectedRows.length === 0) {
      //   this.$message.warning('请至少选择一个指标')
      //   return
      // }
      
      this.$emit('confirm', this.selectedRows)
      this.handleClose()
    },
    
    // 处理样式选项悬浮
    handleStyleHover(style, event) {
      const imageUrl = this.stylePreviewImages[style]
      if (!imageUrl) return
      
      // 移除现有的tooltip
      this.removeTooltip()
      
      // 创建预览图片tooltip
      const tooltip = document.createElement('div')
      tooltip.className = 'style-preview-tooltip'
      tooltip.innerHTML = `
        <div class="preview-content">
          <img src="${imageUrl}" alt="${style}" class="preview-image" />
        </div>
      `
      
      // 设置样式
      Object.assign(tooltip.style, {
        position: 'fixed',
        zIndex: '9999',
        width: 'auto',
        // width: '380px',
        backgroundColor: 'rgba(0, 0, 0, 0)',
        // border: '1px solid #e4e7ed',
        // borderRadius: '4px',
        // boxShadow: '0 2px 12px 0 rgba(0,0,0,.1)',
        // padding: '0',
        // maxWidth: '380px'
      })
      
      document.body.appendChild(tooltip)
      this.previewTooltip = tooltip
      
      // 计算位置
      const rect = event.target.getBoundingClientRect()
      const tooltipRect = tooltip.getBoundingClientRect()
      
      let left = rect.right + 10
      let top = rect.top + (rect.height - tooltipRect.height) / 2
      
      // 防止超出屏幕
      if (left + tooltipRect.width > window.innerWidth) {
        left = rect.left - tooltipRect.width - 10
      }
      if (top < 0) {
        top = 10
      }
      if (top + tooltipRect.height > window.innerHeight) {
        top = window.innerHeight - tooltipRect.height - 10
      }
      
      tooltip.style.left = left + 'px'
      tooltip.style.top = top + 'px'
    },
    
    // 处理样式选项离开
    handleStyleLeave() {
      this.removeTooltip()
    },
    
    // 移除tooltip
    removeTooltip() {
      if (this.previewTooltip) {
        document.body.removeChild(this.previewTooltip)
        this.previewTooltip = null
      }
    },
    
    // 关闭弹窗
    handleClose() {
      this.$emit('input', false)
      // 关闭时清理tooltip
      this.removeTooltip()
    }
  }
}
</script>

<style lang="scss" scoped>
.add-indicator-dialog {
  :deep(.el-dialog) {
    margin-top: 5vh;
  }
  
  .filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #ebeef5;
    
    .filter-left {
      display: flex;
      align-items: center;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .selected-count {
      color: #909399;
      font-size: 14px;
    }
  }
  
  :deep(.el-table) {
    .el-table__body-wrapper {
      // max-height: 60vh;
      overflow-y: auto;
    }
  }
  
  .table-cell-content {
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    
    div {
      margin-top: 4px;
    }
  }
  
  // 地图链接样式
  .map-link {
    color: #409eff;
    text-decoration: none;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  // 评价标准单元格样式
  .judge-type-cell {
    .judge-content {
      white-space: pre-line;
      line-height: 1.4;
      margin-bottom: 4px;
      font-size: 13px;
      max-height: 100px;
      overflow: hidden;
    }
    
    .judge-actions {
      margin-top: 4px;
    }
  }
}

/* 全局样式 - 用于动态创建的tooltip */
:global(.style-preview-tooltip) {
  .preview-content {
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;

    .preview-image {
      width: 300px;
      height: 200px;
      // height: auto;
      // display: block;
      // height: 200px;
      object-fit: cover;
      border-radius: 4px;
      // border: 1px solid #e4e7ed;
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.02);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      }
    }
  }
}

/* 下拉框样式优化 */
:global(.style-select-dropdown) {
  .el-select-dropdown__item {
    padding: 8px 10px;
    transition: all 0.2s ease;
    
    &:hover {
      background-color: #f5f7fa;
      color: #409eff;
    }
    
    span {
      font-weight: 500;
    }
  }
}
</style>